import storageKey from '../configs/storagekey'

const prefix = '_DDXQ_'

const setItem = (key, payload, isSession = false) => {
    if (!(key in storageKey)) {
        throw new Error('invalid storage key: ' + key)
    }

    let realkey = prefix + storageKey[key]
    let jsonData = JSON.stringify(payload)

    if (isSession) {
        sessionStorage.setItem(realkey, jsonData)
    } else {
        localStorage.setItem(realkey, jsonData)
    }
}

const getItem = (key, isSession = false) => {
    if (!(key in storageKey)) {
        throw new Error('invalid storage key: ' + key)
    }

    let realkey = prefix + storageKey[key]
    let jsonData = null

    if (isSession) {
        jsonData = sessionStorage.getItem(realkey)
    } else {
        jsonData = localStorage.getItem(realkey)
    }

    return JSON.parse(jsonData)
}

export default {
    setItem,
    getItem
}